//
//  Message.swift
//  WebSocketDemo
//
//  Created by 姬向阳 on 2020/5/10.
//  Copyright © 2020 SUNNYJ. All rights reserved.
//

import SwiftUI

struct ReceivedText: Codable {
    var leixing: Leixing
    var message: Message?
    var history: [Message]?
    var color: RegisterMessage?

    private enum CodingKeys: String,CodingKey {
        case leixing
        case message
        case history
        case color
    }

    init(from decoder: Decoder) throws {
        let container = try decoder.container(keyedBy: CodingKeys.self)
        leixing = try container.decode(Leixing.self, forKey: .leixing)
        do {
            message = try container.decodeIfPresent(Message.self, forKey: .message)
        } catch  {
            message = nil
        }
        do {
            history = try container.decodeIfPresent([Message].self, forKey: .history)
        } catch {
            history = nil
        }
        do {
            color = try container.decodeIfPresent(RegisterMessage.self, forKey: .color)
        } catch {
            color = nil
        }
    }


}

/// 用来表示消息的结构体
struct Message : Hashable, Codable{
    /// 时间
    let time: String
    /// 头像
    let author: String
    /// 消息文字
    let text: String
    /// Bubble颜色
    let color: String
    /// 是否是我发的消息
    var isMe: Bool = false
    
    private enum CodingKeys: String,CodingKey {
        case time
        case author
        case text
        case color
    }
}

struct RegisterMessage: Codable {
    var color: String
}

enum Leixing: String,Codable {
    case COLOR = "color"
    case HISTORY = "history"
    case MESSAGE = "message"
}

